"""报表页面视图函数模块"""
import logging
import traceback

from flask import request

from air_web.web_flask.bll.report_bll import ReportBll
from air_web.web_flask.common.validator import (
    T_DATE,
    T_INT,
    T_LIST,
    Fields,
    with_validator,
)
from air_web.web_flask.views.base_page import BasePage

logger = logging.getLogger()


class ReportPageValidationFields:
    """报表页面字段验证类"""

    chain_fields = [
        Fields("pre_date", T_DATE, must=True),
        Fields("fol_date", T_DATE, must=True),
        Fields("is_export", T_INT, default=0),
        Fields("on5_list", T_LIST),
        Fields("time_list", T_LIST),
    ]


class ReportPage(BasePage):
    """报表页面视图函数类"""

    @classmethod
    @with_validator(request, ReportPageValidationFields.chain_fields)
    def city_chain(cls):
        """地市环比报表"""
        validation_data = request.validation_data
        pre_date = validation_data.get("pre_date")
        fol_date = validation_data.get("fol_date")
        is_export = validation_data.get("is_export")
        on5_list = validation_data.get("on5_list")
        time_list = validation_data.get("time_list")
        try:
            if is_export:
                res_df = ReportBll().export_chain_excel(
                    pre_date, fol_date, on5_list, time_list
                )
                col_map = {
                    "org_name": "地市",
                    "p_avg": "平均环比压降(万kW)",
                    "p_max": "最大环比压降(万kW)",
                }
                (
                    columns_chinese_dict,
                    round_two_decimal_column,
                    percent_column,
                ) = ({}, [], [])
                for col in res_df.columns:
                    columns_chinese_dict.update(
                        {col: col_map[col] if col in col_map else col}
                    )
                    if "压降值" in col:
                        round_two_decimal_column.append(col)
                        columns_chinese_dict.update({col: col + "(万kW)"})
                    elif col in ["p_avg", "p_max"]:
                        round_two_decimal_column.append(col)
                    elif "压降率" in col:
                        percent_column.append(col)
                        columns_chinese_dict.update({col: col + "(%)"})

                return cls.get_return_excel_file_from_df(
                    data_df=res_df,
                    columns_chinese_dict=columns_chinese_dict,
                    round_two_decimal_column=round_two_decimal_column,
                    percent_column=percent_column,
                    sheet_name="各地市空调负荷环比压降统计表",
                    file_name="环比压降统计表",
                )
            else:
                result = ReportBll().get_city_chain(
                    pre_date, fol_date, on5_list, time_list
                )
                return cls.return_common_func(result)
        except:
            logger.error(traceback.format_exc())
            return cls.return_common_func(-1)
